package root.electronclass.electronclass.personal.fragment.pay_record

import android.app.DatePickerDialog
import android.content.res.ColorStateList
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.DatePicker
import android.widget.TextView
import androidx.appcompat.widget.ListPopupWindow
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.forEach
import androidx.core.view.forEachIndexed
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import root.electronclass.electronclass.R
import root.electronclass.electronclass.common.base.BasicAdapter
import root.electronclass.electronclass.common.base.ViewBindingFragment
import root.electronclass.electronclass.common.util.ToastUtil
import root.electronclass.electronclass.databinding.FragmentPersonalPayRecordBinding
import root.electronclass.electronclass.databinding.FragmentPersonalPayRecordItemBinding
import root.electronclass.electronclass.ext.*
import root.electronclass.electronclass.grade.model.CanteenPayRecord
import root.electronclass.electronclass.grade.model.StuPayRecordQuery
import root.electronclass.electronclass.grade.widget.CircleItem
import root.electronclass.electronclass.grade.widget.LineChartView
import root.electronclass.electronclass.mvp.base.data
import root.electronclass.electronclass.mvp.base.isSuccessful
import root.electronclass.electronclass.mvp.rest.ClassApi
import java.math.BigDecimal
import java.text.DecimalFormat
import java.util.*

/**
 * 个人考勤页面
 * @author Lokiy
 * @date 2023/3/22 23:30
 */
class PersonalPayRecordFragment : ViewBindingFragment<FragmentPersonalPayRecordBinding>() {

    private var pageIndex = 1
    private var type: String? = null //1-7天 2-一个月 3-一学期
    private var startTime: String = ""
    private var endTime: String = ""

    private val itemsAdapter = BasicAdapter<CanteenPayRecord, FragmentPersonalPayRecordItemBinding>(onLoadMore = { getData() }) { holder, item ->
        holder.binding.root.backgroundTintList = ColorStateList.valueOf(if (holder.adapterPosition % 2 == 0) 0 else 0xfF7f8f9)
        holder.binding.itemType.text = item.orderType
        holder.binding.itemName.text = item.orderName.orEmpty().ifEmpty { "-" }
        holder.binding.itemDevice.text = item.deviceName.orEmpty().ifEmpty { "-" }
        holder.binding.itemStatus.text = if (item.iscStatus == 1) "已入账" else "未入账"
        holder.binding.itemAmount.text = item.price
        holder.binding.itemAmount.setTextColor(if (item.price.contains("-")) 0xFF093B5D.toInt() else 0xFF21D976.toInt())

        holder.binding.itemAmountFix.text = "-"
        holder.binding.itemDate.text = item.eventTime
        holder.binding.itemBalance.text = item.balance
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val tabs = arrayOf("近7天", "近1个月", "近3个月")
        val calendar = Calendar.getInstance()
        endTime = calendar.timeInMillis.toDateYyyyMMdd()
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.SECOND, 0)
        calendar.add(Calendar.DAY_OF_YEAR, -7)
        startTime = calendar.timeInMillis.toDateYyyyMMdd()
        binding.tabLayout.tabs(tabs) {
            binding.selectTime.text = "自定义时间"
            binding.selectTime.isSelected = false
            when (it) {
                "近7天" -> calendar.add(Calendar.DAY_OF_YEAR, -7)
                "近1个月" -> calendar.add(Calendar.MONTH, -1)
                "近3个月" -> calendar.add(Calendar.MONTH, -3)
            }
            startTime = calendar.timeInMillis.toDateYyyyMMdd()
            pageIndex = 1
            getData()
        }
        binding.studentRecyclerTitle.root.apply {
            val names = resources.getStringArray(R.array.personal_pay_record_titles)
            forEachIndexed { index, it ->
                val view1: View
                if (it is TextView) {
                    view1 = it
                } else {
                    it as ViewGroup
                    view1 = it.getChildAt(0)
                    view1 as TextView
                }
                view1.setTextColor(0xFFFFFFFF.toInt())
                view1.text = names[index]
            }
            updateLayoutParams<ConstraintLayout.LayoutParams> {
                topMargin = 56
            }
        }
        binding.itemRecycler.adapter = itemsAdapter
        binding.type.text = "消费类目"
        binding.type.setOnClickListener {
            ListPopupWindow(requireContext()).apply {
                anchorView = it
                isModal = true
                val arrays = "全部,充值,在线点餐,学校补助,退单,消费机扣款,退费,海康线下扣款,交易冲正,临时充值".split(",")
                setAdapter(ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, arrays))
                setOnItemClickListener { _, _, position, _ ->
                    dismiss()

                    val selectType = arrays[position]
                    binding.type.text = if (selectType == "全部") "消费类目" else selectType
                    type = if (selectType == "全部") null else selectType
                    pageIndex = 1
                    getData()
                }
            }.show()
        }
        binding.selectTime.setOnClickListener {
            var selectStartTime: String
            var selectEndTime: String
            val df = DecimalFormat("00")
            val calendar = Calendar.getInstance()
            val function: (view: DatePicker, year: Int, month: Int, dayOfMonth: Int) -> Unit = { _, year, month, dayOfMonth ->
                selectStartTime = "$year-${df.format(month + 1)}-${df.format(dayOfMonth)}"
                ToastUtil.showToast(requireActivity(), "请选择自定义结束时间")
                createDialog({ _, year1, month1, dayOfMonth1 ->
                    selectEndTime = "$year1-${df.format(month1 + 1)}-${df.format(dayOfMonth1)}"
                    if (selectEndTime > selectStartTime) {
                        startTime = selectStartTime
                        endTime = selectEndTime
                        binding.tabLayout.selectTab(null)
                        binding.tabLayout.forEach { child ->
                            if (child is ViewGroup) {
                                child.forEach {
                                    it.isSelected = false
                                    it.isActivated = false
                                }
                            }
                        }
                        binding.selectTime.isSelected = true
                        binding.selectTime.text = "$startTime 至 $endTime"
                        pageIndex = 1
                        getData()
                    } else {
                        ToastUtil.showToast(requireActivity(), "开始时间要小于结束时间")
                    }
                }, calendar, "请选择自定义结束时间")
            }
            ToastUtil.showToast(requireActivity(), "请选择自定义开始时间")
            createDialog(function, calendar, "请选择自定义开始时间")
        }
        getData()
        getStatData()
    }

    private fun createDialog(
        function: (view: DatePicker, year: Int, month: Int, dayOfMonth: Int) -> Unit,
        calendar: Calendar,
        title: String
    ) {
        DatePickerDialog(
            requireActivity(),
            function, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)
        ).apply {
            setTitle(title)
        }.show()
    }

    private fun getStatData() {
        //一周统计
        binding.payChart.textFormatter = { "$it%" }
        lifecycleScope.launch(CoroutineExceptionHandler { }) {
            val response = withContext(Dispatchers.IO) {
                ClassApi.service.getStudentPayRecordWeekStat()
            }
            if (response.isSuccessful) {
                val online = response.data.online ?: BigDecimal("0")
                val offline = response.data.offline ?: BigDecimal("0")
                binding.onlinePay.text = online.toPlainString()
                binding.offlinePay.text = offline.toPlainString()
                val total = online.add(offline)
                binding.total.text = DecimalFormat("0.#").format(total.toDouble())
                if (total.toDouble() > 0) {
                    binding.payChart.setData(
                        mutableListOf(
                            CircleItem(0xFF5AD8A6.toInt(), (offline.toDouble() / total.toDouble() * 100).toInt()),
                            CircleItem(0xFF5B8FF9.toInt(), (online.toDouble() / total.toDouble() * 100).toInt()),
                        )
                    )
                }
            } else {
                binding.onlinePay.text = "--"
                binding.offlinePay.text = "--"
                binding.payChart.setData(
                    mutableListOf(
                        CircleItem(0xFF5AD8A6.toInt(), 50),
                        CircleItem(0xFF5B8FF9.toInt(), 50),
                    )
                )
            }
        }

        //一周趋势
        lifecycleScope.launch(CoroutineExceptionHandler { }) {
            val response = withContext(Dispatchers.IO) {
                ClassApi.service.getStudentPayRecordWeekList()
            }
            if (response.isSuccessful) {
                val onlineData = mutableListOf<Float>()
                val offlineData = mutableListOf<Float>()
                val dateList = mutableListOf<String>()
                response.data.forEach {
                    onlineData.add(it.online?.toFloat() ?: 0f)
                    offlineData.add(it.offline?.toFloat() ?: 0f)
                    dateList.add(it.statDate)
                }
                binding.lineChart.horizontalLineCount = 6
                binding.lineChart.data += LineChartView.LineChartData(0xFF5AD8A6.toInt(), offlineData)
                binding.lineChart.data += LineChartView.LineChartData(0xFF5B8FF9.toInt(), onlineData)
                binding.lineChart.yFormatter = { dateList.getOrNull(it)?.toMMdd(yyyyMMddHHmmss) ?: "" }
                binding.lineChart.invalidate()
            }
        }
    }

    private fun getData() {
        if (pageIndex == 1) {
            showProgress("加载中", "", true)
        }
        lifecycleScope.launch(CoroutineExceptionHandler { dismissProgress() }) {
            val response = withContext(Dispatchers.IO) {
                ClassApi.service.getStudentPayRecordPage(StuPayRecordQuery(pageIndex, type, startTime, endTime))
            }
            dismissProgress()
            if (response.isSuccessful) {
                if (pageIndex == 1) {
                    itemsAdapter.notifyChanged(response.data.records)
                } else {
                    itemsAdapter.addAll(response.data.records)
                }
                pageIndex++
            }
        }
    }

}